#!/usr/bin/env python3
"""
数据同步模块安装脚本
自动创建数据库表、初始化权限和路由
"""

import asyncio
import sys
import os
import subprocess
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from app.core.config import settings
from app.core.logger import logger


async def run_sql_script(script_path: str):
    """执行SQL脚本"""
    try:
        logger.info(f"执行SQL脚本: {script_path}")
        
        # 构建MySQL命令
        cmd = [
            'mysql',
            '-h', settings.DB_HOST,
            '-P', str(settings.DB_PORT),
            '-u', settings.DB_USER,
            f'-p{settings.DB_PASSWORD}',
            '-e', f'source {script_path}'
        ]
        
        # 执行命令
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            cwd=project_root
        )
        
        if result.returncode == 0:
            logger.info(f"SQL脚本执行成功: {script_path}")
            return True
        else:
            logger.error(f"SQL脚本执行失败: {result.stderr}")
            return False
            
    except Exception as e:
        logger.error(f"执行SQL脚本异常: {e}")
        return False


async def run_python_script(script_path: str):
    """执行Python脚本"""
    try:
        logger.info(f"执行Python脚本: {script_path}")
        
        # 构建Python命令
        cmd = [sys.executable, script_path]
        
        # 执行命令
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            cwd=project_root
        )
        
        if result.returncode == 0:
            logger.info(f"Python脚本执行成功: {script_path}")
            if result.stdout:
                print(result.stdout)
            return True
        else:
            logger.error(f"Python脚本执行失败: {result.stderr}")
            if result.stderr:
                print(result.stderr)
            return False
            
    except Exception as e:
        logger.error(f"执行Python脚本异常: {e}")
        return False


async def check_dependencies():
    """检查依赖项"""
    logger.info("检查依赖项...")
    
    # 检查MySQL客户端
    try:
        result = subprocess.run(['mysql', '--version'], capture_output=True, text=True)
        if result.returncode != 0:
            logger.error("MySQL客户端未安装或不可用")
            return False
        logger.info(f"MySQL客户端版本: {result.stdout.strip()}")
    except FileNotFoundError:
        logger.error("MySQL客户端未找到，请安装MySQL客户端")
        return False
    
    # 检查Python依赖
    required_packages = ['kafka-python', 'aiomysql', 'asyncpg', 'cx_Oracle', 'pyodbc']
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package.replace('-', '_'))
        except ImportError:
            missing_packages.append(package)
    
    if missing_packages:
        logger.warning(f"以下Python包未安装（可选）: {', '.join(missing_packages)}")
        logger.info("可以运行以下命令安装: pip install " + " ".join(missing_packages))
    
    return True


async def test_database_connection():
    """测试数据库连接"""
    logger.info("测试数据库连接...")
    
    try:
        from app.core.database import AsyncSessionLocal
        
        async with AsyncSessionLocal() as db:
            await db.execute("SELECT 1")
            logger.info("数据库连接测试成功")
            return True
            
    except Exception as e:
        logger.error(f"数据库连接测试失败: {e}")
        return False


async def setup_sync_module():
    """安装数据同步模块"""
    logger.info("开始安装数据同步模块...")
    
    scripts_dir = project_root / "scripts"
    
    # 步骤1: 检查依赖项
    print("🔍 检查依赖项...")
    if not await check_dependencies():
        print("❌ 依赖项检查失败")
        return False
    
    # 步骤2: 测试数据库连接
    print("🔗 测试数据库连接...")
    if not await test_database_connection():
        print("❌ 数据库连接失败")
        return False
    
    # 步骤3: 创建数据库表
    print("📊 创建数据库表...")
    sql_script = scripts_dir / "create_sync_tables.sql"
    if not await run_sql_script(str(sql_script)):
        print("❌ 数据库表创建失败")
        return False
    
    # 步骤4: 初始化权限和路由
    print("🔐 初始化权限和路由...")
    permission_script = scripts_dir / "init_sync_permissions.py"
    if not await run_python_script(str(permission_script)):
        print("❌ 权限初始化失败")
        return False
    
    # 步骤5: 验证安装
    print("✅ 验证安装...")
    if not await verify_installation():
        print("⚠️  安装验证有警告，但基本功能应该可用")
    
    print("🎉 数据同步模块安装完成！")
    return True


async def verify_installation():
    """验证安装结果"""
    try:
        from app.core.database import AsyncSessionLocal
        from sqlalchemy import text
        
        async with AsyncSessionLocal() as db:
            # 检查表是否创建成功
            tables_to_check = [
                'dp_sync_tasks',
                'dp_sync_executions', 
                'dp_sync_logs',
                'dp_sync_field_mappings'
            ]
            
            for table in tables_to_check:
                result = await db.execute(
                    text(f"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{settings.DB_NAME}' AND table_name = '{table}'")
                )
                count = result.scalar()
                if count == 0:
                    logger.error(f"表 {table} 未创建成功")
                    return False
                else:
                    logger.info(f"表 {table} 创建成功")
            
            # 检查权限是否创建成功
            result = await db.execute(
                text("SELECT COUNT(*) FROM dp_permissions WHERE name LIKE 'sync%'")
            )
            permission_count = result.scalar()
            
            if permission_count == 0:
                logger.error("同步相关权限未创建成功")
                return False
            else:
                logger.info(f"创建了 {permission_count} 个同步相关权限")
            
            # 检查路由是否创建成功
            result = await db.execute(
                text("SELECT COUNT(*) FROM dp_routes WHERE path LIKE '/sync%'")
            )
            route_count = result.scalar()
            
            if route_count == 0:
                logger.error("同步相关路由未创建成功")
                return False
            else:
                logger.info(f"创建了 {route_count} 个同步相关路由")
            
            return True
            
    except Exception as e:
        logger.error(f"验证安装失败: {e}")
        return False


def print_usage():
    """打印使用说明"""
    print("""
数据同步模块安装脚本

使用方法:
    python scripts/setup_sync_module.py

功能说明:
    1. 检查系统依赖项
    2. 测试数据库连接
    3. 创建同步相关数据库表
    4. 初始化权限和路由配置
    5. 验证安装结果

注意事项:
    - 确保MySQL服务正在运行
    - 确保数据库配置正确
    - 建议在测试环境先运行
    """)


async def main():
    """主函数"""
    if len(sys.argv) > 1 and sys.argv[1] in ['-h', '--help']:
        print_usage()
        return
    
    try:
        success = await setup_sync_module()
        if success:
            print("\n✅ 数据同步模块安装成功！")
            print("\n下一步:")
            print("1. 重启后端服务")
            print("2. 重启前端服务") 
            print("3. 访问 /sync 页面测试功能")
        else:
            print("\n❌ 数据同步模块安装失败！")
            print("请检查日志信息并解决问题后重试")
            sys.exit(1)
            
    except KeyboardInterrupt:
        print("\n⚠️  安装被用户中断")
        sys.exit(1)
    except Exception as e:
        print(f"\n❌ 安装过程中发生异常: {e}")
        sys.exit(1)


if __name__ == "__main__":
    asyncio.run(main())
